package model.exceptions

import model.exceptions
import play.api.libs.json.{JsError, JsResult, JsValue, Json, Reads, Writes}

import scala.util.Try

object ErrorCode extends Enumeration {
  type ErrorCode = Value

  val SUCCESS: exceptions.ErrorCode.Value = Value(0, "success")
  val CAN_NOT_PROCESS_ERROR: exceptions.ErrorCode.Value =
    Value(1001, "can_not_process_error")

  implicit def reads: Reads[exceptions.ErrorCode.Value] =
    (code: JsValue) =>
      (JsResult.fromTry[ErrorCode] _).curried(Try(ErrorCode(code.as[Int]))) {
        (throwable: Throwable) =>
          JsError(throwable.getMessage)
    }

  implicit def writes: Writes[exceptions.ErrorCode.Value] =
    (obj: ErrorCode) => Json.toJson(obj.id)
}
